package example.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.StrutsStatics;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ValidationAware;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * Interceptor que se encarga de gestionar la sesi�n
 * @author icasado
 *
 */
public class LoginInterceptor extends ActionSupport implements Interceptor{

	private static final String USERNAME = "username";
	private static final String PASSWORD = "password";
	private static final String LOGIN_ATTEMPT = "login_attempt";
	
	/**
	 *  Marca en sesi�n para el usuario logado
	 */
	public static final String USER_HANDLE = "user_handle";
	
	private SecurityManager securityManager;
	
	/**
	 * @see com.opensymphony.xwork2.interceptor.Interceptor#destroy()
	 */
	public void destroy() {}

	/**
	 * @see com.opensymphony.xwork2.interceptor.Interceptor#init()
	 */
	public void init() {}

	/** 
	 * @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
	 */
	public String intercept(ActionInvocation invocation) throws Exception {
		// Obtenemos request y session
	    ActionContext context = invocation.getInvocationContext ();
	    HttpServletRequest request = (HttpServletRequest) context.get(StrutsStatics.HTTP_REQUEST);
	    HttpSession session =  request.getSession (true);

	    // Existe un usuario en sesi�n
	    Object user = session.getAttribute (USER_HANDLE);
	    if (user == null) {
	        String loginAttempt = request.getParameter (LOGIN_ATTEMPT);
	        if (loginAttempt != null && !"".equals(loginAttempt) ) { // The user is attempting to log in.

	            // Process the user's login attempt.
	            if (processLoginAttempt (request, session) ) {
	            	return invocation.invoke();
	            }
				// The login failed. Set an error if we can on the action.
				Object action = invocation.getAction ();
				
				if (action instanceof ValidationAware) {
				    ((ValidationAware) action).addActionError (getText("login.error"));
				}
	        }

	        // Reenviamos a la p�gina de login
	        return "login";
	    }
	    return invocation.invoke();
	}
	
	/**
	 * Comprueba que el login es v�lido con la ayuda del SecurityManager
	 * @param request 
	 * @param session 
	 * @return boolean
	 */
	public boolean processLoginAttempt (HttpServletRequest request, HttpSession session) {
	    // Get the username and password submitted by the user from the HttpRequest.
	    String username = request.getParameter (USERNAME);
	    String password = request.getParameter (PASSWORD);

	    // Use the security manager to validate the user's username and password.
	    Object user = this.securityManager.login (username, password);

	    if (user != null) {
	        // The user has successfully logged in. Store their user object in 
	        // their HttpSession. Then return true.
	        session.setAttribute (USER_HANDLE, user);
	        return true;
	    }
        // The user did not successfully log in. Return false.
        return false;
	}

	/**
	 * @return the securityManager
	 */
	public SecurityManager getSecurityManager() {
		return this.securityManager;
	}

	/**
	 * @param securityManager the securityManager to set
	 */
	public void setSecurityManager(SecurityManager securityManager) {
		this.securityManager = securityManager;
	}

}
